package com.fulihui.weixinsdk.http;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * 用于有传输文件需求的http亲求
 *
 * @author wang_wx
 * @date 2018-07-11
 */
public class MultipartHttpClient implements HttpInvoke {
    private static final Logger logger = LoggerFactory.getLogger("HTTPCLIENT_UTIL_LOG");

    PoolingHttpClientConnectionManager cm;
    CloseableHttpClient httpClient;

    public MultipartHttpClient(int maxTotal, int maxRoute) {
        cm = new PoolingHttpClientConnectionManager();
        // 最大连接数
        cm.setMaxTotal(maxTotal);
        // 单路由最大连接数
        cm.setDefaultMaxPerRoute(maxRoute);
        httpClient = HttpClients.custom().setConnectionManager(cm).build();
    }

    @Override
    public String doGet(HttpRequest request) {
        return null;
    }

    @Override
    public String doPost(HttpRequest request) {
        String resp = null;
        try {
            // 如果有请求文件
            File file = request.getFile();
            if (Objects.nonNull(file)) {
                String fullUrl = HttpUtil.genFullGetUrl(request.getUrl(), request.getParams(), request.getUrlFoot());
                resp = HttpUtil.executePostFile(httpClient, fullUrl, file);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return resp;
    }

    @Override
    public void close() {
        try {
            if (null != httpClient) {
                httpClient.close();
            }
            if (null != cm) {
                cm.close();
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
}